import { Injectable } from '@angular/core'
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http'
import { Observable, throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'
import { AppMessageDialogService } from 'src/app/service/app-message-dialog.service'

export declare class ErrorCollect {
  errTitle: string
  errDetail: string
}

@Injectable({
  providedIn: 'root'
})
export class AppHttpInterceptorProvider implements HttpInterceptor {
  showErrorDialog = true
  constructor(private messageDialog: AppMessageDialogService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone({
      headers: req.headers.append('Content-Type', ['application/json;charset=UTF-8'])
    })
    return next.handle(req).pipe(
      catchError((err: HttpErrorResponse) => {
        console.log(err)
        const errCollect: ErrorCollect = {
          errTitle: '',
          errDetail: ''
        }
        //  Error from Client Side
        if (err.error instanceof ErrorEvent) {
          errCollect.errTitle = `客户端错误`
          errCollect.errDetail = `Error: ${err.error.message}`
        }
        // Error fromServer Side
        else {
          const serverCollect = err.error
          switch (err.status) {
            case 401:
              errCollect.errTitle = '用户认证出错'
              errCollect.errDetail = serverCollect.message ? serverCollect.message : err.message
              break
            case 400:
              errCollect.errTitle = '请求失败，非法参数'
              errCollect.errDetail = serverCollect.message ? serverCollect.message : err.message
              break
            case 500:
              errCollect.errTitle = '服务器响应出错'
              errCollect.errDetail = serverCollect.message ? serverCollect.message : err.message
              break
            default:
              errCollect.errTitle = '未知错误'
              errCollect.errDetail = serverCollect.message ? serverCollect.message : err.message
          }
        }
        if (this.showErrorDialog) this.messageDialog.showMessage(errCollect.errTitle, errCollect.errDetail)
        return throwError(errCollect)
      })
    )
  }

}
